"""
@Project:p8_syl_flask
@File:jwt_auth.py
@Author:郑凯乐
@Date:20:46
"""
import jwt
from flask import current_app,request,g,jsonify
from jwt.exceptions import ExpiredSignatureError,DecodeError
import re

def jwt_authentication():
    # 获取访问路由
    path = request.url_rule

    if re.findall(r"register|code|login|oauth", str(path), re.I):  # re.I 忽略大小写
        # 继续往后走
        return None
    # 获取token
    token = request.headers.get("Authorization")

    g.user_id = None

    # 判单token是否存在
    if token:
        try:
            key = current_app.config.get("SECRET_KEY")
            payload = jwt.decode(token, key=key, algorithms=['HS256'])
            # token 校验成功, 把用户id 写入g 对象
            g.user_id = payload.get('uid')
            # 判断是否是刷新生成的token
            return None

        except ExpiredSignatureError:
            # print("token过期")
            return jsonify(msg="刷新token", code=401) # 返回自定义状态码
        except DecodeError:
            # print("token认证失败，token被篡改")
            return jsonify(msg="请重新登陆！", code=408) # 返回自定义状态码

    return jsonify(msg="请重新登陆！", code=401) # 返回自定义状态码
